﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
namespace DynamicDnsChanger.Extensions.DynDNS
{
    [Export(typeof(IUpdater))]
    public class DynDNS : IPlugin, IUpdater
    {
        private IRequester _Requester;

        public string Name
        {
            get { return "DynDNS"; }
        }

        public event EventHandler<InfoStatus> StatusChange;
        [ImportingConstructor]
        public DynDNS(IRequester Requester)
        {
            
            
        }
        public void Update(string NewIP)
        {
            Contract.Requires(StatusChange != null, "StatusChange");
            
            var username = "";
            var password = "";
            var hostname = "";
            var iniFilePath = String.Concat(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory, @"\DynamicDnsChanger.Extensions.DynDNS.ini");
            if (!File.Exists(iniFilePath))
            {
                this.StatusChange.Invoke(this, new InfoStatus(TypeOfMessage.Error, "Arquivo não localizado: " + iniFilePath));
                return;
            }
            using (var iniFile = new StreamReader(iniFilePath))
            {
                var strLine = iniFile.ReadLine();

                while (strLine != null)
                {
                    var pair = strLine.Split('=');
                    if (pair.Count() > 1)
                    {
                        if (pair[0].Trim() == "username")
                        {
                            username = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "password")
                        {
                            password = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "hostname")
                        {
                            hostname = pair[1].Trim();
                        }
                    }
                    strLine = iniFile.ReadLine();
                }
            };
            //Criar um request exclusivo para poder informar os dados de autenticação
            _Requester = new InternalRequester(username, password);
            //http://dyn.com/support/developers/api/perform-update/                     
            var DynDNSApiUrl = "https://members.dyndns.org/nic/update?hostname={0}&myip={1}&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG";
            
            var r = _Requester.GetString(String.Format(DynDNSApiUrl,hostname, NewIP));
            StatusChange.Invoke(this, new InfoStatus(r.ToLower().Contains("success") ? TypeOfMessage.Success : TypeOfMessage.Error, r.ToLower().Contains("success") ? String.Format("hosts or groups: {0} as a new IP > {1}", hostname , NewIP) : r));

        }
    }
}
